<script lang="ts" setup>
import { login } from '@/api/user'
import type { FormRules, FormInstance } from 'element-plus'
import type { LoginForm } from '@/types/user'
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/user'
import { useRouter, useRoute } from 'vue-router'

const store = useUserStore()
const router = useRouter()
const route = useRoute()

const ruleForm = reactive({
  adminname: 'admin',
  password: '123456'
})

const rules = reactive<FormRules<LoginForm>>({
  adminname: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
    { min: 4, max: 15, message: '用户名必须是5-15位', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 4, max: 15, message: '密码必须是5-15位', trigger: 'blur' }
  ]
})

const ruleFormRef = ref<FormInstance>()

const onLogin = async () => {
  if (!ruleFormRef) return

  ruleFormRef.value?.validate(async valid => {
    // 所有的表单校验通过
    if (valid) {
      const res = await login(ruleForm)

      if (res.data.code === 200) {
        // token存储到pinia中
        store.setToken(res.data.data.token)
        // 消息提示
        ElMessage({
          message: res.data.message,
          duration: 800,
          type: 'success'
        })

        // 跳转到Layout (/)
        if (route.query.redirect) {
          router.push(route.query.redirect as string)
        } else {
          router.push('/')
        }
      } else {
        console.log('----xxx---')
        ElMessage.error(res.data.message)
      }
    }
  })
}
</script>

<template>
  <div class="login-container">
    <el-card class="box-card">
      <h3 style="text-align: center">嗨购商城后台管理系统</h3>
      <el-divider border-style="dashed" />
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        class="demo-ruleForm"
        size="large"
        label-position="left"
      >
        <el-form-item label-width="80px" label="用户名" prop="adminname">
          <el-input v-model="ruleForm.adminname" />
        </el-form-item>
        <el-form-item label-width="80px" label="密码" prop="password">
          <el-input v-model="ruleForm.password" show-password />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" style="width: 100%" @click="onLogin"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
.login-container {
  height: 100%;
  .box-card {
    width: 440px;
    height: 316px;
  }
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
